const CFG = require('./config');
const FUN = require('./comm/func');
const mqttConn = require('./utils/mqttConn');
const PMR = require('./utils/policyManger');
const {CombTopic} = require('./utils/devConfig');

// 检测是不是本地运行
if (FUN.isLocal()) {
  console.log("\n\nIs Local Host:", require("os").hostname());
} else {
  console.log("\n\nIs Remote Srv:", require("os").hostname());
}

FUN.SleepMs(2000); // 延时两秒等mqtt服务器启动完成

//启动一个mqtt链接对象
mqttConn.newClient('admin.3'+FUN.rand(12345678,99999999), (conn)=>{
  let Topics = [];

  //区分调试环境和部署环境，不同环境的发往不同主题
  if (FUN.isLocal()) Topics.push('php/policy/local');
  else Topics.push('php/policy/api-srv');

  // 订阅主题
  for (let type of [CFG.T_Wpass, CFG.T_Gw, CFG.T_Wdev, CFG.T_Dtu]) {
    Topics.push(CombTopic('tx', '+'+type, '+'));
    Topics.push(CombTopic('rx', '+'+type, '+'));
    Topics.push(CombTopic('var', '+'+type, '+'));
    Topics.push(CombTopic('data', '+'+type, '+'));
  }
  Topics.push('srv/debug');
  console.log('[Sub Topic]', Topics.join(', '));

  conn.msgHdrs = [];
  conn.msgHdrs.push(PMR);
  PMR.mqConn = conn;
  PMR.mqPub = (topic, payload, opts={retain:false}) => { // mqtt发包函数
    if (FUN.isLocal()) { console.log('N>>',topic,payload);return; }//防止本地调试时，对在线设备重复发包
    conn.publish(topic, payload, opts);
    if (opts.log) console.log('>>>', topic,payload);
  }
  conn.subscribe(Topics, (err) => { if(err)console.log('err1:',err) });
  console.log('start monitor');
  PMR.Init(process.argv[2]); // 初始化策略管理器
})

